from flask import Flask, render_template
from pymongo import MongoClient
import matplotlib.pyplot as plt
import io
import base64
import pandas as pd

app = Flask(__name__)

# 连接到 MongoDB
client = MongoClient('localhost', 27017)  # 本地MongoDB服务器
db = client['WLQ_db']  # 数据库名称
collection = db['WLQ_col']  # 集合名称

# 查询数据
def get_weather_data():
    data = collection.find()
    weather_data = []
    for doc in data:
        weather_data.append({
            "date": doc["date"],
            "weather": doc["weather"],
            "high_temp": doc["high_temp"],
            "low_temp": doc["low_temp"],
            "night_weather": doc["night_weather"]
        })
    return weather_data

# 绘制温度图表
def plot_temperature_data():
    # 获取数据
    data = get_weather_data()

    # 转换为DataFrame
    df = pd.DataFrame(data)

    # 绘制高温和低温的图表
    fig, ax = plt.subplots(figsize=(10, 5))
    ax.plot(df["date"], df["high_temp"], label='High Temp (°C)', marker='o', linestyle='-', color='red')
    ax.plot(df["date"], df["low_temp"], label='Low Temp (°C)', marker='o', linestyle='-', color='blue')

    ax.set_xlabel("Date")
    ax.set_ylabel("Temperature (°C)")
    ax.set_title("Temperature Trends Over Days")
    ax.legend()

    # 保存为图片
    img = io.BytesIO()
    plt.savefig(img, format='png')
    img.seek(0)
    img_base64 = base64.b64encode(img.getvalue()).decode('utf-8')
    return img_base64

@app.route('/')
def index():
    # 获取天气数据并生成图表
    img_base64 = plot_temperature_data()
    return render_template('index.html', img_base64=img_base64)

if __name__ == '__main__':
    app.run(debug=True)
